package com.adk.backend.service.impl;

import com.adk.backend.mapper.InventoryListMapper;
import com.adk.backend.mapper.ReportMapper;
import com.adk.backend.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报表统计服务实现类
 */
@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    
    @Autowired
    private InventoryListMapper inventoryListMapper;
    
    @Autowired
    private ReportMapper reportMapper;
    
    @Override
    public Map<String, Object> getOrderStatistics(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        // 解析参数
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        Long uid = params.get("uid") != null ? Long.valueOf(params.get("uid").toString()) : null;
        
        // 转换日期为时间戳
        Integer startTime = null;
        Integer endTime = null;
        if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date start = sdf.parse(startDate);
                Date end = sdf.parse(endDate);
                startTime = (int) (start.getTime() / 1000);
                endTime = (int) (end.getTime() / 1000 + 86400 - 1); // 当天的23:59:59
            } catch (Exception e) {
                log.error("日期解析失败", e);
            }
        }
        
        // 总订单数（根据PHP：select count(id) as total from order_list where ...）
        Long totalOrders = reportMapper.countTotalOrders(startTime, endTime, uid);
        result.put("totalOrders", totalOrders != null ? totalOrders : 0L);
        
        // 待审核订单数（根据PHP：select count(id) as total from order_list where ... and is_confirm=0）
        Long pendingOrders = reportMapper.countPendingConfirmOrders(startTime, endTime, uid);
        result.put("pendingOrders", pendingOrders != null ? pendingOrders : 0L);
        
        // 总重量（空运：ship_type in (1,3)，根据PHP：sum(ship_weigth) where ship_type in (1,3)）
        BigDecimal totalWeight = reportMapper.sumTotalWeightAir(startTime, endTime, uid);
        result.put("totalWeight", totalWeight != null ? totalWeight : BigDecimal.ZERO);
        
        // 总体积（海运：ship_type in (2,4)，根据PHP：sum(ship_weigth) where ship_type in (2,4)）
        BigDecimal totalVolume = reportMapper.sumTotalVolumeSea(startTime, endTime, uid);
        result.put("totalVolume", totalVolume != null ? totalVolume : BigDecimal.ZERO);
        
        // 沙特空运订单数（ship_type=1, order_no is not null）
        Long saAirOrders = reportMapper.countOrdersByShipType(1, startTime, endTime, uid);
        result.put("saAirOrders", saAirOrders != null ? saAirOrders : 0L);
        
        // 沙特海运订单数（ship_type=2, order_no is not null）
        // 注意：PHP中只统计ship_type=2，没有包含ship_type=7（海运整柜）
        Long saSeaOrders = reportMapper.countOrdersByShipType(2, startTime, endTime, uid);
        result.put("saSeaOrders", saSeaOrders != null ? saSeaOrders : 0L);
        
        // 阿联酋空运订单数（ship_type=3, order_no is not null）
        Long uaeAirOrders = reportMapper.countOrdersByShipType(3, startTime, endTime, uid);
        result.put("uaeAirOrders", uaeAirOrders != null ? uaeAirOrders : 0L);
        
        // 阿联酋海运订单数（ship_type=4, order_no is not null）
        Long uaeSeaOrders = reportMapper.countOrdersByShipType(4, startTime, endTime, uid);
        result.put("uaeSeaOrders", uaeSeaOrders != null ? uaeSeaOrders : 0L);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getFinanceStatistics(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        // 总账单金额
        result.put("totalAmount", BigDecimal.ZERO);
        
        // 已付款金额
        result.put("paidAmount", BigDecimal.ZERO);
        
        // 未付款金额
        result.put("unpaidAmount", BigDecimal.ZERO);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getWarehouseStatistics(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        // 总库存数量
        Map<String, Object> countParams = new HashMap<>();
        Long totalInventory = inventoryListMapper.countInventoryListByCondition(countParams);
        result.put("totalInventory", totalInventory);
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getOrdersReportBySales(Map<String, Object> params) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 解析日期参数
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        Long uid = params.get("uid") != null ? Long.valueOf(params.get("uid").toString()) : null;
        
        Integer startTime = null;
        Integer endTime = null;
        if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date start = sdf.parse(startDate);
                Date end = sdf.parse(endDate);
                startTime = (int) (start.getTime() / 1000);
                endTime = (int) (end.getTime() / 1000 + 86400 - 1); // 当天的23:59:59
            } catch (Exception e) {
                log.error("日期解析失败", e);
            }
        }
        
        // 判断是否需要查询（有日期范围或指定业务员）
        boolean hasSearch = (startTime != null && endTime != null) || (uid != null && uid > 0);
        
        if (!hasSearch) {
            return result;
        }
        
        // 查询业务员列表（user_type in (4, 6, 35)）
        List<Map<String, Object>> salesList = reportMapper.selectOrdersReportBySales(params);
        
        // 为每个业务员统计订单数据
        for (Map<String, Object> sales : salesList) {
            Long salesUid = Long.valueOf(sales.get("id").toString());
            
            // 如果指定了业务员，只统计该业务员
            if (uid != null && uid > 0 && !salesUid.equals(uid)) {
                continue;
            }
            
            // 统计订单总数
            Long totalOrders = reportMapper.countOrdersBySalesUid(salesUid, startTime, endTime);
            sales.put("qty", totalOrders);
            
            // 如果订单数为0，跳过（后续会过滤）
            if (totalOrders == 0) {
                continue;
            }
            
            // 统计空运重量（ship_type in (1,3)）
            BigDecimal totalGw = reportMapper.sumOrdersWeightBySalesUidAndShipType(
                salesUid, Arrays.asList(1, 3), startTime, endTime);
            sales.put("totalGw", totalGw != null ? totalGw : BigDecimal.ZERO);
            
            // 统计海运重量（ship_type in (2,7,4)）
            BigDecimal totalVw = reportMapper.sumOrdersWeightBySalesUidAndShipType(
                salesUid, Arrays.asList(2, 7, 4), startTime, endTime);
            sales.put("totalVw", totalVw != null ? totalVw : BigDecimal.ZERO);
            
            // 统计KSA空运订单数（ship_type=1, order_no is not null）
            Long ksaAirTotal = reportMapper.countOrdersBySalesUidAndShipType(salesUid, 1, startTime, endTime);
            sales.put("totalKsaAir", ksaAirTotal != null ? ksaAirTotal : 0L);
            
            // 统计KSA海运订单数（ship_type in (2,7), order_no is not null）
            // 注意：这里需要分别统计ship_type=2和ship_type=7
            Long ksaSeaTotal2 = reportMapper.countOrdersBySalesUidAndShipType(salesUid, 2, startTime, endTime);
            Long ksaSeaTotal7 = reportMapper.countOrdersBySalesUidAndShipType(salesUid, 7, startTime, endTime);
            sales.put("totalKsaSea", (ksaSeaTotal2 != null ? ksaSeaTotal2 : 0L) + (ksaSeaTotal7 != null ? ksaSeaTotal7 : 0L));
            
            // 统计UAE空运订单数（ship_type=3, order_no is not null）
            Long uaeAirTotal = reportMapper.countOrdersBySalesUidAndShipType(salesUid, 3, startTime, endTime);
            sales.put("totalUaeAir", uaeAirTotal != null ? uaeAirTotal : 0L);
            
            // 统计UAE海运订单数（ship_type=4, order_no is not null）
            Long uaeSeaTotal = reportMapper.countOrdersBySalesUidAndShipType(salesUid, 4, startTime, endTime);
            sales.put("totalUaeSea", uaeSeaTotal != null ? uaeSeaTotal : 0L);
            
            result.add(sales);
        }
        
        // 按订单数量排序（降序）
        result.sort((a, b) -> {
            Long qtyA = Long.valueOf(a.get("qty").toString());
            Long qtyB = Long.valueOf(b.get("qty").toString());
            return qtyB.compareTo(qtyA);
        });
        
        // 过滤掉订单数为0的记录
        result = result.stream()
            .filter(sales -> Long.valueOf(sales.get("qty").toString()) > 0)
            .collect(Collectors.toList());
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getTradeOrderAwbList(Map<String, Object> params) {
        List<Map<String, Object>> rawList = reportMapper.selectTradeOrderAwbList(params);
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Boolean> awbIndex = new HashMap<>();
        
        // 处理AWB去重
        for (Map<String, Object> item : rawList) {
            String awb = item.get("awb") != null ? item.get("awb").toString().trim() : null;
            if (awb == null || awb.isEmpty()) {
                continue;
            }
            
            // 使用正则按非字母数字字符拆分（兼容空格、-、,、;等）
            String[] awbList = awb.split("[^a-zA-Z0-9]+");
            
            for (String awbItem : awbList) {
                String cleanAwb = awbItem.trim().replace("\"", "");
                if (cleanAwb.isEmpty() || cleanAwb.length() < 6) {
                    continue;
                }
                
                // 检查是否已存在（去重）
                if (awbIndex.containsKey(cleanAwb)) {
                    continue;
                }
                
                // 添加到结果数组
                Map<String, Object> newItem = new HashMap<>();
                newItem.put("id", item.get("id"));
                newItem.put("awb", cleanAwb);
                newItem.put("orderNo", item.get("order_no"));
                newItem.put("portName", item.get("port_name"));
                newItem.put("ccShort", item.get("cc_short"));
                result.add(newItem);
                
                // 标记已添加
                awbIndex.put(cleanAwb, true);
            }
        }
        
        return result;
    }
    
    @Override
    public Map<String, Object> getTradeOrderStatistics(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        // 解析参数
        Integer shipType = params.get("shipType") != null ? Integer.valueOf(params.get("shipType").toString()) : null;
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        
        // 验证参数
        if (shipType == null || shipType <= 0) {
            result.put("code", 0);
            result.put("qty", 0);
            result.put("msg", "请选择运输方式");
            return result;
        }
        
        if (startDate == null || startDate.isEmpty() || endDate == null || endDate.isEmpty()) {
            result.put("code", 0);
            result.put("qty", 0);
            result.put("msg", "请选择日期范围");
            return result;
        }
        
        // 获取贸易订单提单号列表（已去重）
        List<Map<String, Object>> awbList = getTradeOrderAwbList(params);
        
        // 统计唯一提单号数量
        int uniqueAwbCount = awbList.size();
        
        result.put("code", 1);
        result.put("qty", uniqueAwbCount);
        result.put("msg", "总计" + uniqueAwbCount + "个");
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getTradeShipTypes() {
        return reportMapper.selectTradeShipTypes();
    }
}


